/**
 * Copyright (c) 2018 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package io.renren.modules.sys.service.impl;

import cn.hutool.json.JSONUtil;
import com.alibaba.druid.support.json.JSONUtils;
import com.mysql.jdbc.StringUtils;
import io.renren.common.constant.Constant;
import io.renren.common.exception.ErrorCode;
import io.renren.common.exception.RenException;
import io.renren.common.service.impl.BaseServiceImpl;
import io.renren.common.utils.ConvertUtils;
import io.renren.common.utils.HttpContextUtils;
import io.renren.common.utils.PermissionsUtils;
import io.renren.common.utils.TreeUtils;
import io.renren.modules.security.service.ShiroService;
import io.renren.modules.security.user.UserDetail;
import io.renren.modules.sys.dao.SysMenuDao;
import io.renren.modules.sys.dto.SysMenuDTO;
import io.renren.modules.sys.entity.SysMenuEntity;
import io.renren.modules.sys.enums.SuperAdminEnum;
import io.renren.modules.sys.service.SysLanguageService;
import io.renren.modules.sys.service.SysMenuService;
import io.renren.modules.sys.service.SysRoleMenuService;
import org.apache.ibatis.exceptions.PersistenceException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Service
public class SysMenuServiceImpl extends BaseServiceImpl<SysMenuDao, SysMenuEntity> implements SysMenuService {
	@Autowired
	private SysRoleMenuService sysRoleMenuService;
	@Autowired
	private SysLanguageService sysLanguageService;

	@Autowired
	private PermissionsUtils permissionsUtils;

	@Autowired
	private ShiroService shiroService;

	@Transactional(rollbackFor = Exception.class)
	public void batchMenuList() {
		// 代码中所有菜单&权限
		Map<String, List<SysMenuDTO>> returnResult = permissionsUtils.test(RequiresPermissions.class);
		// 现在的所有菜单权限
		Set<String> set = shiroService.getAllPermissions(null);
		// 所有的菜单
		List<SysMenuDTO> menuDTOList = getAllMenuList();
		Set<String> menuNameSet = new HashSet<>();
		// 将所有菜单权限都加入到 一个集合
		for (SysMenuDTO sysMenuDTO : menuDTOList) {
			menuNameSet.add(sysMenuDTO.getName());
		}

		// 判断要插入到菜单，按钮 ，权限是否已经存在，如果存在则不再重新保存
		// 为空的也不保存
		returnResult.forEach((key, list) -> {
			if (!menuNameSet.contains(key)) {
				for (SysMenuDTO dto : list) {
					if (StringUtils.isEmptyOrWhitespaceOnly(dto.getName())) {
						continue;
					}
					if (isContainsPermissions(set, dto.getPermissions())) {
						continue;
					}
					System.out.println(dto.getType());
					save(dto);
				}
				;
			}
		});
	}

	private boolean isContainsPermissions(Set<String> set, String permissions) {
		String[] str = permissions != null ? permissions.split(",") : null;
		if (str == null) {
			return false;
		}
		for (String s : str) {
			if (set.contains(s)) {
				return true;
			}
		}
		return false;
	}

	@Override
	public SysMenuDTO get(Long id) {
		SysMenuEntity entity = baseDao.getById(id, HttpContextUtils.getLanguage());

		SysMenuDTO dto = ConvertUtils.sourceToTarget(entity, SysMenuDTO.class);

		return dto;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void save(SysMenuDTO dto) {
		SysMenuEntity entity = ConvertUtils.sourceToTarget(dto, SysMenuEntity.class);

		//保存菜单
		insert(entity);
		saveLanguage(entity.getId(), "name", entity.getName());
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void update(SysMenuDTO dto) {
		SysMenuEntity entity = ConvertUtils.sourceToTarget(dto, SysMenuEntity.class);

		//上级菜单不能为自身
		if(entity.getId().equals(entity.getPid())){
			throw new RenException(ErrorCode.SUPERIOR_MENU_ERROR);
		}

		//更新菜单
		updateById(entity);
		saveLanguage(entity.getId(), "name", entity.getName());
	}

	@Override
	@Transactional
	public void changeIShow(Long id, Integer iShow) {
		List<SysMenuEntity> list = this.baseDao.getListPid(id);
		if(list != null && list.size() > 0){
			for (SysMenuEntity e:list){
				e.setIShow(iShow);
				changeIShow(e.getId(),iShow);
			}
			updateBatchById(list);
		}
		SysMenuEntity entity = new SysMenuEntity();
		entity.setId(id);
		entity.setIShow(iShow);
		updateById(entity);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void delete(Long id) {
        //删除菜单
        deleteById(id);

        //删除菜单国际化
        sysLanguageService.deleteLanguage("sys_menu", id);

        //删除角色菜单关系
        sysRoleMenuService.deleteByMenuId(id);
    }

    @Override
    public void clear(List<Long> ids) {
        baseDao.clear(ids);
        ids.clear();
    }

	@Override
	public List<SysMenuDTO> getAllMenuList(Integer type) {
		List<SysMenuEntity> menuList = baseDao.getMenuList(type, null, HttpContextUtils.getLanguage());

		List<SysMenuDTO> dtoList = ConvertUtils.sourceToTarget(menuList, SysMenuDTO.class);

		return TreeUtils.build(dtoList, Constant.MENU_ROOT);
	}

	private List<SysMenuDTO> getAllMenuList() {
		List<SysMenuEntity> menuList = baseDao.getMenuList(0, null, HttpContextUtils.getLanguage());

		List<SysMenuDTO> dtoList = ConvertUtils.sourceToTarget(menuList, SysMenuDTO.class);

		return dtoList;
	}

	@Override
	public List<SysMenuDTO> getUserMenuList(UserDetail user, Integer type) {
		List<SysMenuEntity> menuList;

		//系统管理员，拥有最高权限
		if (user.getSuperAdmin() == SuperAdminEnum.YES.value()) {
			menuList = baseDao.getMenuList(type, 1, HttpContextUtils.getLanguage());
		} else {
			menuList = baseDao.getUserMenuList(user.getId(), type, HttpContextUtils.getLanguage());
		}

		List<SysMenuDTO> dtoList = ConvertUtils.sourceToTarget(menuList, SysMenuDTO.class);

		return TreeUtils.build(dtoList);
	}

	@Override
	public List<SysMenuDTO> getListPid(Long pid) {
		List<SysMenuEntity> menuList = baseDao.getListPid(pid);

		return ConvertUtils.sourceToTarget(menuList, SysMenuDTO.class);
	}

	private void saveLanguage(Long tableId, String fieldName, String fieldValue){
		sysLanguageService.saveOrUpdate("sys_menu", tableId, fieldName, fieldValue, HttpContextUtils.getLanguage());
	}

}